<template>
  <div class="createPost-container">
    <el-form ref="postForm" :model="postForm" :rules="rules" class="form-container">

      <sticky :z-index="10" :class-name="'sub-navbar '+postForm.status">
        <div class="Iinfo-submit">
          <el-button v-loading="loading" style="margin-left: 10px;" type="success" @click="submitForm">发布</el-button>
          <el-button v-loading="loading" type="warning" @click="draftForm">保存草稿</el-button>
        </div>
      </sticky>

      <div class="createPost-main-container">
        <el-form-item style="margin-bottom: 40px;" prop="title">
          <MDinput v-model="postForm.title" :maxlength="100" name="name" required>标题</MDinput>
        </el-form-item>
        <el-row>
          <el-col :span="12">
            <div class="postInfo-container">
              <el-form-item label-width="70px" label="作者" class="postInfo-container-item">
                <el-input v-model="postForm.fromName" placeholder="请填写作者信息" />
              </el-form-item>
            </div>
          </el-col>
          <el-col :span="12">
            <el-form-item label-width="70px" label="类型" class="postInfo-container-item">
              <el-select v-model="postForm.categoryId" placeholder="请选择类型">
                <el-option v-for="item in categoryList" :key="item.id" :label="item.value" :value="item.id" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item prop="content" style="margin-bottom: 30px;">
          <Tinymce ref="editor" v-model="postForm.content" :height="400" />
        </el-form-item>
      </div>
    </el-form>
  </div>
</template>

<script>
import Tinymce from '@/components/Tinymce'
import MDinput from '@/components/MDinput'
import Sticky from '@/components/Sticky'
import { addIndustryInfo, editIndustryInfo, getIndustryInfo } from '@/api/industryInfo'
import { getInfoConfigList } from '@/api/config'

const defaultForm = {
  status: 0,
  title: '', // 文章题目
  content: '', // 文章内容
  summary: '', // 文章摘要
  imgUrl: '', // 文章图片
  id: undefined
}

export default {
  name: 'InfoDetail',
  components: { Tinymce, MDinput, Sticky },
  props: {
    isEdit: {
      type: Boolean,
      default: false
    }
  },
  data() {
    const validateRequire = (rule, value, callback) => {
      if (value === '') {
        console.log(rule)
        // this.$message({
        //   message: rule.field + '为必传项',
        //   type: 'error'
        // })
        callback(new Error(rule.field + '为必传项'))
      } else {
        callback()
      }
    }
    return {
      postForm: Object.assign({}, defaultForm),
      loading: false,
      userListOptions: [],
      categoryList: [],
      rules: {
        imgUrl: [{ validator: validateRequire }],
        title: [{ validator: validateRequire }],
        content: [{ validator: validateRequire }]
      },
      tempRoute: {}
    }
  },
  computed: {
    contentShortLength() {
      return this.postForm.summary.length
    }
  },
  created() {
    this.fetchInfoConfigList()
    if (this.isEdit) {
      const id = this.$route.params && this.$route.params.id
      this.fetchData(id)
    }

    // Why need to make a copy of this.$route here?
    // Because if you enter this page and quickly switch tag, may be in the execution of the setTagsViewTitle function, this.$route is no longer pointing to the current page
    // https://github.com/PanJiaChen/vue-element-admin/issues/1221
    this.tempRoute = Object.assign({}, this.$route)
  },
  methods: {
    fetchInfoConfigList() {
      getInfoConfigList().then(res => {
        this.categoryList = res.data
      })
    },
    fetchData(id) {
      getIndustryInfo(id).then(response => {
        this.postForm = response.data
        console.log('-----------', this.postForm)

        // just for test
        // this.postForm.title += `   Article Id:${this.postForm.id}`
        // this.postForm.content_short += `   Article Id:${this.postForm.id}`

        // set tagsview title
        this.setTagsViewTitle()

        // set page title
        this.setPageTitle()
      }).catch(err => {
        console.log(err)
      })
    },
    setTagsViewTitle() {
      // const title = 'Edit Article'
      // const route = Object.assign({}, this.tempRoute, { title: `${title}-${this.postForm.id}` })
      // this.$store.dispatch('tagsView/updateVisitedView', route)
    },
    setPageTitle() {
      const title = 'Edit Article'
      document.title = `${title} - ${this.postForm.id}`
    },
    submitForm() {
      console.log(this.postForm)
      this.$refs.postForm.validate(valid => {
        if (valid) {
          this.loading = true
          this.postForm.status = 1
          if (this.isEdit) {
            editIndustryInfo(this.postForm).then(res => {
              this.$notify({
                title: '成功',
                message: '案例修改成功',
                type: 'success',
                duration: 2000
              })
            })
          } else {
            addIndustryInfo(this.postForm).then(res => {
              this.$notify({
                title: '成功',
                message: '案例发布成功',
                type: 'success',
                duration: 2000
              })
            })
          }
          this.loading = false
          this.$router.push('/info/list')
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    draftForm() {
      if (this.postForm.content.length === 0 || this.postForm.title.length === 0) {
        this.$message({
          message: '请填写必要的标题和内容',
          type: 'warning'
        })
        return
      }
      this.postForm.status = 0
      if (this.isEdit) {
        editIndustryInfo(this.postForm).then(res => {
          this.$notify({
            title: '成功',
            message: '案例草稿修改成功',
            type: 'success',
            duration: 2000
          })
        })
      } else {
        addIndustryInfo(this.postForm).then(res => {
          this.$notify({
            title: '成功',
            message: '案例草稿保存成功',
            type: 'success',
            duration: 2000
          })
        })
      }
      this.$router.push('/Iinfo/list')
    }
  }
}
</script>

<style lang="scss" scoped>
@import "~@/styles/mixin.scss";

.createPost-container {
  position: relative;
  .Iinfo-submit {
    text-align: right;
    padding: 12px 45px 0 0;
  }

  .createPost-main-container {
    padding: 0px 45px 20px 50px;

    .postInfo-container {
      position: relative;
      @include clearfix;
      margin-bottom: 10px;

      .postInfo-container-item {
        float: left;
      }
      .el-icon-upload:hover {
        display: block;
      }
    }
  }

  .word-counter {
    width: 60px;
    position: absolute;
    right: 10px;
    top: 0px;
  }
}

.article-textarea ::v-deep {
  textarea {
    padding-right: 40px;
    resize: none;
    border: none;
    border-radius: 0px;
    border-bottom: 1px solid #bfcbd9;
  }
}
</style>
